package org.example.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtils {

    private static final Logger LOG = LoggerFactory.getLogger(FileUtils.class);

    public static void createFileIfNotExists(Path p) {
        File file = p.toFile();
        try {
            if (!file.exists()) {
                boolean newFile = file.createNewFile();
                LOG.info("Create new File, {}", file.getAbsolutePath());
            } else {
                LOG.info("File exists");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void createFileIfExists(Path p) {
        File file = p.toFile();
        if (file.exists()) {
            boolean deleted = file.delete();
            if (!deleted) {
                throw new RuntimeException("File delete fails");
            }
        }
        createFileIfNotExists(p);
    }

    public static void createDirIfNotExists(Path p) {
        File folder = p.toFile();
        if (!folder.exists() && !folder.isDirectory()) {
            boolean mkdirs = folder.mkdirs();
            LOG.info("Create Dir: {}", folder);
        } else {
            LOG.info("Dir has already exists.");
        }
    }

    public static void createDirIfExists(Path p) {
        File folder = p.toFile();
        if (folder.exists()) {
            boolean deleted = folder.delete();
            createDirIfNotExists(p);
        }
    }

    public static void checkPathExists(Path p) {
        boolean exists = Files.exists(p);
        if (!exists) {
            LOG.error("{} not exists", p.toFile().getAbsolutePath());
            throw new RuntimeException("File not exists.");
        }
    }

    public static String pathJoinString(String base, String... fileName) {
        return Paths.get(base, fileName).toString();
    }

    public static Path pathJoin(String base, String... fileName) {
        return Paths.get(base, fileName);
    }
}
